package fm.dongman.animefm.view.fragment;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import org.jetbrains.annotations.NotNull;

import java.util.List;

import fm.dongman.animefm.R;
import fm.dongman.animefm.contractlib.contract.VideoPlayContract;
import fm.dongman.animefm.contractlib.model.VideoSideTagModel;
import fm.dongman.animefm.view.util.ActivityHelper;
import fm.dongman.animefm.view.util.SystemHelper;
import fm.dongman.animefm.view.util.ToastHelper;
import fm.dongman.modellib.StaticArea.Injection;
import fm.dongman.presenterlib.presenter.VideoPlayPresenter;

/**
 * 用于播放动漫
 * Created by KUIGE on 2017/12/4.
 */
public class WebViewVideoFragment extends BaseFragment implements VideoPlayContract.IVideoPlayView{
    private VideoPlayContract.IVideoPlayPresenter mPresenter; // 数据控制器
    private List<VideoSideTagModel> mSideTagList; // 网站播放器标识
    private WebView mWebView;
    private WebSettings mSettings;
    private RelativeLayout mWebViewRoot;
    private String Url;
    private FrameLayout mVideoContainer;
    private Toolbar mToolbar;
    private ProgressBar mProgressBar; // 进度条

    public WebViewVideoFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_web_view_video, container, false);
        initView(view);
        new VideoPlayPresenter(this, Injection.provideVideoPlayRepository());
        return view;
    }

    /**
     * 获取布局 View
     *
     * @param view 布局 root
     */
    private void initView(View view) {
        mWebView = (WebView) view.findViewById(R.id.id_WebView_Video);
        mWebViewRoot = (RelativeLayout) view.findViewById(R.id.mWebViewSuper);
        mVideoContainer = (FrameLayout) view.findViewById(R.id.id_WebView_Video_hs);
        mToolbar = (Toolbar) view.findViewById(R.id.mTbWebViewToolBar);
        mProgressBar = (ProgressBar) view.findViewById(R.id.mTbWebViewProgress);
    }

    @Override
    public void initData() {
        mSettings = mWebView.getSettings();
    }

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    public void bindData() {
        mProgressBar.setMax(100);
        mWebView.setWebChromeClient(new MyWebChromeClient());
        mWebView.loadUrl(Url);
        mSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        mSettings.setMediaPlaybackRequiresUserGesture(true);
        mSettings.setJavaScriptEnabled(true);
        mSettings.setUseWideViewPort(true);
        mSettings.setAllowFileAccess(true); // 允许访问文件
        mSettings.setSupportZoom(true); // 支持缩放
        mSettings.setLoadWithOverviewMode(true);
        mSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); // 不加载缓存内容

        mSettings.setDomStorageEnabled(true); // 是否支持 DOM 储存
        mSettings.setSupportMultipleWindows(true);// 支持多窗口
//        mSettings.setPluginState(WebSettings.PluginState.ON); // 5.0以下
        // 优酷 5.0 以上需要加这个
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        mWebView.addJavascriptInterface(new JsObject(), "onClick");

        mToolbar.setPadding(0,SystemHelper.INSTANCE.getStatusBarHeight(getActivity()),0,0);
        // 返回按钮点击事件
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityHelper.INSTANCE.backActivity(getActivity());
            }
        });
    }

    @Override
    public void showVideoSideTag(List<VideoSideTagModel> list) {
        // 各大网页播放器获取标准（播放器的 class）
        mSideTagList = list;
        mWebView.setWebViewClient(new CustomWebClient());
    }

    @Override
    public void onStart() {
        super.onStart();
        mPresenter.startLoad();
    }

    @Override
    public void onResume() {
        super.onResume();
        mWebView.onResume();
    }

    /**
     * 设置链接
     *
     * @param url 链接
     */
    public void setUrl(String url) {
        Url = url;
    }

    private class MyWebChromeClient extends WebChromeClient {
        private CustomViewCallback mCallBack;

        /**
         * 打开view
         *
         * @param view     视图
         * @param callback 回调
         */
        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            fullScreen();
            mWebView.setVisibility(View.GONE);
            mToolbar.setVisibility(View.GONE);
            mVideoContainer.setVisibility(View.VISIBLE);
            mVideoContainer.addView(view);
            mCallBack = callback;
            super.onShowCustomView(view, callback);
        }

        /**
         * 隐藏view
         */
        @Override
        public void onHideCustomView() {
            fullScreen();
            if (mCallBack != null) {
                mCallBack.onCustomViewHidden();
            }
            mWebView.setVisibility(View.VISIBLE);
            mToolbar.setVisibility(View.VISIBLE);
            mVideoContainer.removeAllViews();
            mVideoContainer.setVisibility(View.GONE);
            super.onHideCustomView();
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            if (mProgressBar.getProgress() < 100) {
                mProgressBar.setVisibility(View.VISIBLE);
            } else {
                mProgressBar.setVisibility(View.GONE);
            }
            mProgressBar.setProgress(newProgress);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (title != null)
                mToolbar.setTitle(title);
        }
    }

    private class CustomWebClient extends WebViewClient {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            view.loadUrl("javascript:document.getElementsByClassName('" + getTagByUrl(url) +
                    "')[0].addEventListener('click',function(){onClick.fullscreen();return false;});");
        }
    }

    /**
     * 根据地址获取全屏按钮元素 class
     *
     * @param url 播放地址
     * @return 全屏按钮元素 class
     */
    public String getTagByUrl(String url) {
        if (mSideTagList == null) {
            return "";
        }
        for (VideoSideTagModel model : mSideTagList) {
            if (url.contains(model.getMSideName())) {
                return model.getMFullVideoTag();
            }
        }
        return "";
    }

    /**
     * 全屏
     */
    private void fullScreen() {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            SystemHelper.INSTANCE.setFullScreen(getActivity());
            getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {
            SystemHelper.INSTANCE.quitFullScreen(getActivity());
            getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }

    /**
     * 退出全屏
     */
    public void backFull() {
        fullScreen();
    }

    private class JsObject {
        @JavascriptInterface
        public void fullscreen() {
            //监听到用户点击全屏按钮
            fullScreen();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        mWebView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mWebViewRoot.removeView(mWebView);
        if (mWebView != null) {
            mWebView.destroy();
            mWebView = null;
        }
    }

    @Override
    public void setPresenter(VideoPlayContract.IVideoPlayPresenter iVideoPlayPresenter) {
        mPresenter = iVideoPlayPresenter;
    }

    @Override
    public void showNoNetwork() {
        ToastHelper.getInstance(getActivity()).showWarn("没有网络！");
    }

    @Override
    public void showRefreshFailed() {
        ToastHelper.getInstance(getActivity()).showError(getString(R.string.str_refresh_failed));
    }

    @Override
    public boolean isActive() {
        return isAdded();
    }

    @NotNull
    @Override
    public Context getViewContext() {
        return getActivity();
    }
}
